//
//  SearchResultViewController.m
//  copyrightTrading
//
//  Created by edz on 2020/10/21.
//  Copyright © 2020 郭子一. All rights reserved.
//

#import "SearchResultViewController.h"
#import "VideoCell.h"
#import "PopView.h"
#import "TZImagePickerController.h"
#import <MobileCoreServices/MobileCoreServices.h>
@interface SearchResultViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,PopViewDelegate,TZImagePickerControllerDelegate,UINavigationControllerDelegate, UITextFieldDelegate>

@property (nonatomic, strong) UICollectionView *stateCollectionView; // 模式列表
@property (nonatomic, strong) PopView *popView;
@property (nonatomic, strong)NSMutableArray *selectedPhotos;
@property (nonatomic, strong) NSMutableArray *selectedAssets;
@property (nonatomic, copy) NSString*fileStringName;

@end

@implementation SearchResultViewController

//- (NSMutableArray *)dataArray
//{
//    if (!_dataArray) {
//        _dataArray = [NSMutableArray array];
//    }
//    return _dataArray;
//}
//
//- (void)setDataArray:(NSMutableArray *)dataArray
//{
//    _dataArray = dataArray;
//    [self.stateCollectionView reloadData];
//}

- (void)setDataArray:(NSMutableArray *)dataArray
{
    _dataArray = dataArray;
    [self.stateCollectionView reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)tapImgChooseSourceType:(NSInteger)sourctType
{
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 columnNumber:4 delegate:self pushPhotoPickerVc:YES];
    imagePickerVc.maxImagesCount = 1;
    if (sourctType == 1) {
        imagePickerVc.allowPickingImage = YES;
        imagePickerVc.allowPickingVideo = NO;
        imagePickerVc.allowTakePicture = YES;   // 在内部显示拍照片按
    } else {
        imagePickerVc.allowPickingImage = NO;
        imagePickerVc.allowPickingVideo = YES;
        imagePickerVc.allowTakeVideo = YES;   // 在内部显示拍视频按
    }
    imagePickerVc.showSelectedIndex = YES;
    imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
    [imagePickerVc setUiImagePickerControllerSettingBlock:^(UIImagePickerController *imagePickerController) {
        imagePickerController.videoQuality = UIImagePickerControllerQualityTypeHigh;
    }];
    WeakSelf(self);
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        [weakSelf.selectedPhotos removeAllObjects];
        [weakSelf.selectedAssets removeAllObjects];
        weakSelf.selectedPhotos = [NSMutableArray arrayWithArray:@[photos[0]]];
        weakSelf.selectedAssets = [NSMutableArray arrayWithArray:@[assets[0]]];
//        self.popView.img.image = photos[0];
//        self.popView.contentLab.hidden = YES;
        weakSelf.popView.contentLab.text = @"图片文件上传成功";
    }];
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}

#pragma mark == 视频选择代理方法
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingVideo:(UIImage *)coverImage sourceAssets:(PHAsset *)asset {
    _selectedPhotos = [NSMutableArray arrayWithArray:@[coverImage]];
    _selectedAssets = [NSMutableArray arrayWithArray:@[asset]];
    // open this code to send video / 打开这段代码发送视频
    WeakSelf(self);
    [[TZImageManager manager] getVideoOutputPathWithAsset:asset presetName:AVAssetExportPresetLowQuality success:^(NSString *outputPath) {
        weakSelf.fileStringName = outputPath;
//        weakSelf.popView.img.image = coverImage;
        weakSelf.popView.contentLab.text = @"视频文件上传成功";
        // NSData *data = [NSData dataWithContentsOfFile:outputPath];
        NSLog(@"视频导出到本地完成,沙盒路径为:%@",outputPath);
        // Export completed, send video here, send by outputPath or NSData
        // 导出完成，在这里写上传代码，通过路径或者通过NSData上传
        
    } failure:^(NSString *errorMessage, NSError *error) {
        NSLog(@"视频导出失败:%@,error:%@",errorMessage, error);
    }];
}

- (void)PopViewEnsureClickWithType:(PopViewType)type content:(nonnull NSString *)content
{
    NSLog(@"%ld",(long)type);
    if (type == KVideoType) {
        if (!self.selectedAssets.count) {
            return;
        }
        [MBProgressHUD showLoadingView:self.view andText:@"搜索中"];
        [[APIManager sharedNetManager] searchWithParams:@{@"file":self.fileStringName} url:@"videoSearch" success:^(NSInteger code, NSDictionary * _Nonnull dict) {
            [MBProgressHUD hideLoadingView:self.view];
            self.dataArray = dict[@"data"][@"search_list"];
        } failure:^(NSInteger code, NSError * _Nonnull error) {
            [MBProgressHUD hideLoadingView:self.view];
        } isVideo:YES];
    } else if (type == KFaceType) {
        if (!self.selectedPhotos.count) {
            return;
        }
        [MBProgressHUD showLoadingView:self.view andText:@"搜索中"];
        [[APIManager sharedNetManager] searchWithParams:@{@"file":self.selectedPhotos[0]} url:@"faceSearch" success:^(NSInteger code, NSDictionary * _Nonnull dict) {
            [MBProgressHUD hideLoadingView:self.view];
            self.dataArray = dict[@"data"][@"search_list"];
        } failure:^(NSInteger code, NSError * _Nonnull error) {
            [MBProgressHUD hideLoadingView:self.view];
        } isVideo:NO];
    } else if (type == KPictureType) {
        if (!self.selectedPhotos.count) {
            return;
        }
        [MBProgressHUD showLoadingView:self.view andText:@"搜索中"];
        [[APIManager sharedNetManager] searchWithParams:@{@"file":self.selectedPhotos[0]} url:@"logoSearch" success:^(NSInteger code, NSDictionary * _Nonnull dict) {
            [MBProgressHUD hideLoadingView:self.view];
            self.dataArray = dict[@"data"][@"search_list"];
        } failure:^(NSInteger code, NSError * _Nonnull error) {
            [MBProgressHUD hideLoadingView:self.view];
        } isVideo:NO];
    }
}

- (void)setupUI
{
    UIView *headerView = [UIView new];
    headerView.backgroundColor = RGB_VALUE(0xDC0000);
    [self.view addSubview:headerView];
    [headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.offset(0);
        make.height.mas_equalTo(Height_NavBar);
    }];
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setImage:[UIImage imageNamed:@"whiteBack"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [backBtn setHitEdgeInsets:UIEdgeInsetsMake(-15, -15, -15, -15)];
    [headerView addSubview:backBtn];
    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.offset(-14);
        make.left.offset(18);
        make.width.height.mas_equalTo(16);
    }];
    
    UILabel *titleLabel = [UILabel new];
    titleLabel.text = @"搜索结果";
    titleLabel.font = JSS_MEDIUM_FONT(17);
    titleLabel.textColor = RGB_VALUE(0xFFFFFF);
    titleLabel.textAlignment = NSTextAlignmentCenter;
    [headerView addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.offset(-9);
        make.centerX.offset(0);
        make.width.mas_equalTo(135);
        make.height.mas_equalTo(24);
    }];
    
    YCShadowView *searchViewleft = [[YCShadowView alloc] init];
    searchViewleft.backgroundColor = RGB_VALUE(0x767680);
    searchViewleft.alpha = 0.33;
    [searchViewleft yc_cornerRadius:10 byRoundingCorners:UIRectCornerTopLeft | UIRectCornerBottomLeft];
    [self.view addSubview:searchViewleft];
    [searchViewleft mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(16);
        make.height.mas_equalTo(36);
        make.top.equalTo(headerView.mas_bottom).offset(10);
        make.width.mas_equalTo(106);
    }];
    
    // 为了让搜索按钮颜色突出
    UIView *searchView1 = [[UIView alloc] init];
    searchView1.layer.masksToBounds = YES;
    searchView1.layer.cornerRadius = 10;
    searchView1.clipsToBounds = YES;
    [self.view addSubview:searchView1];
    [searchView1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(16);
        make.right.offset(-16);
        make.height.mas_equalTo(36);
        make.top.equalTo(headerView.mas_bottom).offset(10);
    }];
    
    UIView *searchView = [[UIView alloc] init];
    searchView.backgroundColor = RGB_VALUE(0x767680);
    searchView.layer.masksToBounds = YES;
    searchView.layer.cornerRadius = 10;
    searchView.alpha = 0.33;
    searchView.clipsToBounds = YES;
    [searchView1 addSubview:searchView];
    [searchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.offset(0);
    }];
    
    UIButton *pictureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [pictureBtn setImage:[UIImage imageNamed:@"pictureSearch"] forState:UIControlStateNormal];
    [pictureBtn addTarget:self action:@selector(pictureBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [searchView addSubview:pictureBtn];
    [pictureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(15);
        make.centerY.offset(0);
        make.width.height.mas_equalTo(21);
    }];
    
    UIButton *taibiaoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [taibiaoBtn setImage:[UIImage imageNamed:@"taibiaoSerach"] forState:UIControlStateNormal];
    [taibiaoBtn addTarget:self action:@selector(taibiaoBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [searchView addSubview:taibiaoBtn];
    [taibiaoBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(pictureBtn.mas_right).offset(7);
        make.centerY.offset(0);
        make.width.height.mas_equalTo(21);
    }];
    
    UIButton *videoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [videoBtn setImage:[UIImage imageNamed:@"videoSearch"] forState:UIControlStateNormal];
    [videoBtn addTarget:self action:@selector(videoBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [searchView addSubview:videoBtn];
    [videoBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(taibiaoBtn.mas_right).offset(7);
        make.centerY.offset(0);
        make.width.height.mas_equalTo(21);
    }];
    
    UITextField *searchTextF = [[UITextField alloc] init];
    searchTextF.placeholder = @"输入内容来搜索";
    searchTextF.delegate = self;
    searchTextF.font = JSS_MEDIUM_FONT_3;
    searchTextF.returnKeyType = UIReturnKeySearch;
    [searchView1 addSubview:searchTextF];
    [searchTextF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(searchViewleft.mas_right).offset(10);
        make.right.offset(-35);
        make.centerY.offset(0);
        make.height.mas_equalTo(searchView.mas_height);
    }];
    
    UIButton *searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [searchBtn setImage:[UIImage imageNamed:@"popViewSearch"] forState:UIControlStateNormal];
    [searchBtn addTarget:self action:@selector(searchBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [searchView1 addSubview:searchBtn];
    [searchBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(-12);
        make.centerY.offset(0);
        make.width.height.mas_equalTo(21);
    }];
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.sectionInset = UIEdgeInsetsMake(20, 16, 20, 16);
    layout.minimumLineSpacing = 14;
    layout.minimumInteritemSpacing = 7;
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    self.stateCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    self.stateCollectionView.delegate = self;
    self.stateCollectionView.dataSource = self;
    self.stateCollectionView.backgroundColor = RGB_VALUE(0xF5F5F5);
//    self.stateCollectionView.backgroundColor = UIColor.clearColor;
    self.stateCollectionView.showsHorizontalScrollIndicator = NO;
    [self.stateCollectionView registerClass:[VideoCell class] forCellWithReuseIdentifier:@"VideoCell"];
    [self.view addSubview:self.stateCollectionView];
    [self.stateCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.bottom.offset(0);
        make.top.equalTo(searchView.mas_bottom).offset(10);
    }];
    
//    @weakify(self)
//    self.stateCollectionView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
//        @strongify(self)
//        self.pageIndex ++;
//        [self requestData];
//    }];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    NSLog(@"%@",textField.text);
    if (NULLString(textField.text)) {
        [self showMessage:@"搜索内容不能为空"];
        return NO;
    }
    NSDictionary *paramDic = @{
        @"type":@"",
        @"sort_id":@"",
        @"keyword":textField.text,
        @"page":@(1),
        @"limit":@(10),
        @"is_commend":@(0)
    };
    [[APIManager sharedNetManager] requestWithMethod:HttpRequestTypeGet URLString:@"material" parameters:paramDic done:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        SearchResultViewController *vc = [[SearchResultViewController alloc] init];
        vc.dataArray = responseObject[@"data"][@"list"][@"list"];
        [self pushVc:vc];
    } fail:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        
    }];
    return YES;
}

// 视频搜索
- (void)videoBtnClick
{
    self.popView = [[PopView alloc] initWithStyle:KVideoType];
    self.popView.contentLab.hidden = NO;
    self.popView.delegate = self;
}

// 图片搜索
- (void)taibiaoBtnClick
{
    self.popView = [[PopView alloc] initWithStyle:KFaceType];
    self.popView.contentLab.hidden = NO;
    self.popView.delegate = self;
}
// 台标搜索
- (void)pictureBtnClick
{
    self.popView = [[PopView alloc] initWithStyle:KPictureType];
    self.popView.contentLab.hidden = NO;
    self.popView.delegate = self;
}

- (void)searchBtnClick
{
    
}

- (void)backBtnClick
{
    [self pop];
}

- (void)requestData
{
    [[APIManager sharedNetManager] searchWithParams:@{} url:@"" success:^(NSInteger code, NSDictionary * _Nonnull dict) {
        
    } failure:^(NSInteger code, NSError * _Nonnull error) {
        
    } isVideo:YES];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake((kDeviceWidth - 32 - 7)/2, 134);
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    VideoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"VideoCell" forIndexPath:indexPath];
    cell.dataDic = self.dataArray[indexPath.row];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    [self pushVideoDetailVCWithID:self.dataArray[indexPath.row][@"id"]];
}
@end
